home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 5051 < prev    next >
Encoding:
Text File  |  1996-08-05  |  1.5 KB  |  50 lines

  1. Path: castle.nando.net!news
  2. From: actuary@nando.net   (Bill McCarthy)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: truncation function?
  5. Date: 12 Feb 1996 02:21:32 GMT
  6. Organization: News & Observer Public Access
  7. Message-ID: <4fm87c$6mi@castle.nando.net>
  8. References: <4fjc0k$nev$1@mhadg.production.compuserve.com>
  9. Reply-To: actuary@nando.net (Bill McCarthy)
  10. NNTP-Posting-Host: grail2419.nando.net
  11. X-Newsreader: IBM NewsReader/2 v1.2
  12.  
  13. In <4fjc0k$nev$1@mhadg.production.compuserve.com>, Steve Eckmann <71055.1153@CompuServe.COM> writes:
  14. >I need a truncation function "float trunc(float in; int precision)" that
  15. >takes a float and a precision spec and returns the input float truncated to
  16. >"precision" decimal digits. Similarly for "round". This seems so simple
  17. >that I hesitate to ask, but on the other hand, my attempt (using sprintf
  18. >and sscanf) yields incorrect results sometimes. Thanks.
  19.  
  20. Here's a sample trunc() function which uses doubles instead of floats:
  21.  
  22. #include <stdio.h>
  23. #include <stdlib.h>
  24. #include <math.h>
  25.  
  26. double trunc( double x, int n )      /* rounds toward zero */
  27. {
  28.    double         pown;
  29.    static double  power[] = { 1, 10, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
  30.                               1E9, 1E10, 1E11, 1E12, 1E13, 1E14 };
  31.  
  32.    if ( n < 0 || n >= sizeof( power ) / sizeof( power[0] ) )
  33.    {
  34.       fprintf( stderr, "trunc() precision range error.\n" );
  35.       exit( EXIT_FAILURE );
  36.    }
  37.    
  38.    pown = power[n];
  39.  
  40.    if ( x < 0 )
  41.       return -floor( -x * pown ) / pown;
  42.    else
  43.       return floor( x * pown ) / pown;
  44. }
  45.  
  46. Bill McCarthy
  47. actuary@nando.net
  48. Wendell, NC  USA
  49.  
  50.